//
//  RepairDetailV2ViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/7/25.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "RepairDetailV2ViewController.h"
#import "RepairDetailV2TableViewCell.h"

#define kCellName @"RepairDetailV2TableViewCell"

@interface RepairDetailV2ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    
}
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableArray *dabiaoGeShuArray;
@end

@implementation RepairDetailV2ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UISetting];
    if (_jinriStatus.integerValue == 0) {//待维护,和维护成功
        [self loadData];
    }else{//已维护
        [self loadDataJinRi];
    }
}

- (void)UISetting{
    _dataArray = [NSMutableArray array];
    _dabiaoGeShuArray = [NSMutableArray array];
    _tableView.layer.masksToBounds = YES;
    _tableView.layer.cornerRadius = 10;
    _tableView.backgroundColor = [kWhiteColor colorWithAlphaComponent:0.9];
}

#pragma mark - 网络请求

- (void)loadData{
    [self.hub hideAnimated:YES];
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    NSString *dateNUM = [BGDateHelper getTimeStempByString:_dateString havehh:NO];
    NSString *needDateNUM ;
    if (_status.integerValue == 0) {
        needDateNUM = [NSString stringWithFormat:@"%lld",dateNUM.longLongValue - 86400];
    }else{
        needDateNUM = [NSString stringWithFormat:@"%lld",dateNUM.longLongValue];
    }
    
    NSString *needDate = [BGDateHelper getTimeArrayByTimeString:needDateNUM][0];
    [[AFClient shareInstance] waitingRepairDetailByEid:kUserId date:needDate charging_info_ids:_ids progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        NSLog(@"具体 -> %@",responseBody);
        if ([responseBody[@"code"] integerValue] == 200) {
            for (NSDictionary *dic in responseBody[@"data"]) {
                WaitingRepairDetailModel *model = [[WaitingRepairDetailModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                
                if (![dic[@"charging_info_id"] isKindOfClass:[NSNull class]]) {
                    model.charging_info_id = dic[@"charging_info_id"];
                }
                
                if (_storeType.integerValue == 4) {//WiFi
                    
                    if (model.use_num.integerValue > 0) {
                        [_dabiaoGeShuArray addObject:model];
                    }
                }else{
                    if (model.online_time.integerValue >=120) {
                        [_dabiaoGeShuArray addObject:model];
                    }
                }

                [_dataArray addObject:model];
            }
            
            if (_dataArray.count > 0) {
                WaitingRepairDetailModel *model = _dataArray.firstObject;
                _labelTongjiRiqi.text = [NSString stringWithFormat:@"统计日期：%@",model.date];
                
                //达标率或达标个数
                if (_storeType.integerValue == 4) {//mima
                    _labelDabiaoNum.text = [NSString stringWithFormat:@"设备使用率：%.0lf%%",_dabiaoGeShuArray.count*100.00/_dataArray.count];

                }else{
                    _labelDabiaoNum.text = [NSString stringWithFormat:@"在线时长超过2小时：%ld",_dabiaoGeShuArray.count];

                }
            }
            
            [_tableView reloadData];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)loadDataJinRi{
    [self.hub hideAnimated:YES];
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    NSString *dateNUM = [BGDateHelper getTimeStempByString:_dateString havehh:NO];
    NSString *needDateNUM ;
    if (_status.integerValue == 0) {
        needDateNUM = [NSString stringWithFormat:@"%lld",dateNUM.longLongValue - 86400];
    }else{
        needDateNUM = [NSString stringWithFormat:@"%lld",dateNUM.longLongValue];
    }
    
    if (_jinriStatus.integerValue == 1) {
        needDateNUM = [NSString stringWithFormat:@"%lld",dateNUM.longLongValue];
    }
    
    NSString *needDate = [BGDateHelper getTimeArrayByTimeString:needDateNUM][0];
    [[AFClient shareInstance] waitingRepairDetailJinRiByEid:kUserId date:needDate charging_info_ids:_ids progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        NSLog(@"具体 -> %@",responseBody);
        if ([responseBody[@"code"] integerValue] == 200) {
            for (NSDictionary *dic in responseBody[@"data"]) {
                WaitingRepairDetailModel *model = [[WaitingRepairDetailModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                
                if (![dic[@"charging_info_id"] isKindOfClass:[NSNull class]]) {
                    model.charging_info_id = dic[@"charging_info_id"];
                }
                
                [_dataArray addObject:model];
            }
            
            if (_dataArray.count > 0) {
                WaitingRepairDetailModel *model = _dataArray.firstObject;
                _labelTongjiRiqi.text = [NSString stringWithFormat:@"统计日期：%@",model.date];
            }
            
            [_tableView reloadData];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}


#pragma mark - 点击事件

- (IBAction)backButtonClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (IBAction)WenHaoButtonClick:(UIButton *)sender {
    NSString *message = @"时间说明：\n纳入第二日待维护的店铺 是由第一日晚10点前设备在线时长决定\n所以设备统计时长日期显示第一日";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    //paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    //行间距
    paragraphStyle.lineSpacing = 5.0;
    NSDictionary * attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0], NSParagraphStyleAttributeName : paragraphStyle};
    NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:message];
    [attributedTitle addAttributes:attributes range:NSMakeRange(0, message.length)];
    // 下面这句话用了KVC ，将attributes的值给了alert
    [alert setValue:attributedTitle forKey:@"attributedMessage"];//attributedTitle\attributedMessage
    //end ---
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RepairDetailV2TableViewCell *cell = (RepairDetailV2TableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCellName];
    WaitingRepairDetailModel *model = _dataArray[indexPath.row];
    [cell showDataWithModel:model withType:_jinriStatus storeType:_storeType];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
